const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    movements: [],
    courseName: null,
    positions: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const courseName = wx.getStorageSync('courseName');
    const positionsJson = wx.getStorageSync('positions');
    const positions = JSON.parse(positionsJson);
    const positionTrains = app.globalData.positionTrains;
    const movements = [];
    positionTrains.forEach(function(item) {
      if (item.name === courseName) {
        const list = item.movements;
        list.forEach(function(name) {
          movements.push({
            name,
            selected: false
          });
        });
      }
    });
    this.setData({
      movements,
      courseName,
      positions
    });
  },
  getEmsValue: function(position) {
    const positions = this.data.positions;
    const size = positions.length;
    for (let i = 0; i < size; i++) {
      const selectPosition = positions[i];
      if (position === selectPosition.position) {
        return selectPosition[selectPosition.columnName + '1'];
      }
    }
  },
  select: function(e) {
    const name = e.currentTarget.dataset.name;
    const movements = this.data.movements;
    movements.forEach(function(item) {
      if (item.name === name) {
        item.selected = !item.selected;
      }
    });
    this.setData({
      movements
    });
  },
  confirm: function() {
    const movements = this.data.movements;
    const positionTrains = app.globalData.positionTrains;
    const courseName = this.data.courseName;
    const positions = [];
    const programs = [];
    const that = this;
    wx.showLoading({
      title: '处理中...'
    });
    positionTrains.forEach(function(positionTrain) {
      if (courseName === positionTrain.name) {
        if (positionTrain.normal) {
          positionTrain.normal.forEach(function(item) {
            const emsValue = that.getEmsValue(item) || 0;
            positions.push({
              position: item,
              strongValue: emsValue
            });
          });
        }
      }
    });
    movements.forEach(function(item) {
      if (item.selected) {
        programs.push(item.name);
      }
    });
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    const trainPrograms = prevPage.data.trainPrograms;
    programs.forEach(function(name) {
      const arr = trainPrograms.filter(function(item) {
        return item.name === name;
      });
      if (!arr || arr.length == 0) {
        trainPrograms.push({
          id: Math.random(),
          name,
          strongOption: 'NORMAL',
          items: positions
        });
      }
    });
    prevPage.setData({
      trainPrograms
    });
    wx.hideLoading();
    wx.navigateBack({
      delta: 1
    });
  }
})